package com.hzhjhh.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import lombok.Data;

@Data
public class DBUtils {

	private String resourcePath = "mybatis-config.xml";

	private static SqlSessionFactoryBuilder sFactoryBuilder;
	private static SqlSessionFactory sessionFactory;
	private static volatile DBUtils dbUtils;

	public SqlSessionFactoryBuilder getSqlSessFB() {
		if (Objects.isNull(sFactoryBuilder)) {
			synchronized (dbUtils) {
				sFactoryBuilder = new SqlSessionFactoryBuilder();
			}
		}
		return sFactoryBuilder;
	}

	public SqlSessionFactory getSqlSessFactory() {
		InputStream inputStream = null;
		try {
			sFactoryBuilder = getSqlSessFB();
			synchronized (resourcePath) {
				inputStream = Resources.getResourceAsStream(this.getResourcePath());				
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return sFactoryBuilder.build(inputStream);
	}
	
	public SqlSession getSession(boolean autoCommit) {
		SqlSessionFactory sessionFactory = getSqlSessFactory();
		return sessionFactory.openSession(autoCommit);
	}
	
	public void closeSession(SqlSession session) {
		if (Objects.nonNull(session)) {
			session.close();
		}
	}
	
	private DBUtils() {
		
	}
	
	public static DBUtils getInstance() {
		if (Objects.isNull(dbUtils)) {
			synchronized (DBUtils.class) {
				if (Objects.isNull(dbUtils)) {
					dbUtils = new DBUtils();					
				}
			}
		}
		return dbUtils;
	}
	
	public static SqlSession getSqlSession(boolean autoCommit) {
		return getInstance().getSession(autoCommit);
	}
}
